package com.zz.inventory.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.io.IOException;

import com.alibaba.fastjson2.JSON;
import com.zz.inventory.domain.SystemLogs;
import com.zz.inventory.service.ISystemLogsService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.zz.inventory.domain.SysUser;
import com.zz.inventory.service.ISysUserService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

import static com.ruoyi.common.core.utils.ip.IpUtils.getIpAddr;

/**
 * 用户信息Controller
 * 
 * @author zz
 * @date 2025-07-02
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISystemLogsService iSystemLogsService;

    /**
     * 查询用户信息列表
     */
    @RequiresPermissions("platform:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser sysUser)
    {
        startPage();
        List<SysUser> list = sysUserService.selectSysUserList(sysUser);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @RequiresPermissions("platform:user:export")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser sysUser)
    {
        List<SysUser> list = sysUserService.selectSysUserList(sysUser);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @RequiresPermissions("platform:user:query")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return success(sysUserService.selectSysUserByUserId(userId));
    }

    /**
     * 新增用户信息
     */
    @RequiresPermissions("platform:user:add")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysUser sysUser)
    {
        return toAjax(sysUserService.insertSysUser(sysUser));
    }

    /**
     * 修改用户信息
     */
    @RequiresPermissions("platform:user:edit")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysUser sysUser) {

        // 记录操作开始日志
        SystemLogs startLog = new SystemLogs();
        startLog.setLogTime(new Date());
        startLog.setLogLevel("INFO");
        startLog.setSourceModule("用户管理");
        startLog.setUserId(sysUser.getUserId()); // 设置用户ID

        // 组装操作描述（包含状态变更信息）
        String statusDesc = sysUser.getStatus() != null ?
                (sysUser.getStatus().equals("0") ? "停用" : "启用") : "未知状态";
        startLog.setAction("更改学校账户状态：" + statusDesc);

        // 记录请求参数和状态变更详情
        startLog.setMessage("请求参数: " + JSON.toJSONString(sysUser) +
                ", 状态变更: " + statusDesc);

        iSystemLogsService.insertSystemLogs(startLog);

        try {
            // 执行更新并获取结果
            int result = sysUserService.updateSysUser(sysUser);

            // 记录操作结果日志
            SystemLogs resultLog = new SystemLogs();
            resultLog.setLogTime(new Date());
            resultLog.setLogLevel("INFO");
            resultLog.setSourceModule("用户管理");
            resultLog.setUserId(sysUser.getUserId());
            resultLog.setAction("更改学校账户状态结果：" + (result > 0 ? "成功" : "失败"));
            resultLog.setMessage("更新结果: " + (result > 0 ? "成功" : "失败") +
                    ", 影响行数: " + result);
            iSystemLogsService.insertSystemLogs(resultLog);

            return toAjax(result);
        } catch (Exception e) {
            // 记录异常日志
            SystemLogs errorLog = new SystemLogs();
            errorLog.setLogTime(new Date());
            errorLog.setLogLevel("ERROR");
            errorLog.setSourceModule("用户管理");
            errorLog.setUserId(sysUser.getUserId());
            errorLog.setAction("更改学校账户状态异常");
            errorLog.setMessage("更新异常: " + e.getMessage() +
                    ", 请求参数: " + JSON.toJSONString(sysUser));
            iSystemLogsService.insertSystemLogs(errorLog);

            return AjaxResult.error("状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户信息
     */
    @RequiresPermissions("platform:user:remove")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(sysUserService.deleteSysUserByUserIds(userIds));
    }
}
